<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {

	public function __construct()
	{
	     parent::__construct();
	}
	
	public function login()
	{
		if($this->input->post())
		{
			$user_id = $this->input->post('user_id',TRUE);
			$password = $this->input->post('password',TRUE);
			
			$this->db->where('user_id', $user_id);
			$this->db->where('password', md5($password));
			
			$result = $this->db->get('user')->row();
			if($result){
				$this->session->set_userdata('id', $result->id);
				$this->session->set_userdata('user_id', $result->user_id);
				$this->session->set_userdata('user_name', $result->user_name);
				
				print_r($this->session->all_userdata());
				redirect('main');
			}
			else
			{
				echo "error";
				exit;
			}
		}
		else
		{
			$this->load->view('layout_header');
			$this->load->view('user/login');
			$this->load->view('layout_footer');
		}
	}
	
	public function logout()
	{
		$this->session->set_userdata('id');
		$this->session->set_userdata('user_id');
		$this->session->set_userdata('user_name');
		redirect('user/login');
	}
	
	public function signup()
	{
		$this->load->view('layout_header');
		$this->load->view('user/signup');
		$this->load->view('layout_footer');
	}
	
	public function signup_ajax()
	{
		$check = $this->_check_signup();
		if($check > 0)
		{
			$data = array(
				'user_id' => $this->input->post('user_id',TRUE),
				'password' => md5($this->input->post('password',TRUE)),
				'user_name' => $this->input->post('user_name',TRUE)
			);
			$this->db->insert('user',$data);
			echo 1;
		}
		else
			echo $check;
	}
	
	public function check_user_id()
	{
		$user_id = $this->input->post('user_id',TRUE);
		echo $this->_check_user_id($user_id);
	}
	
	function _check_user_id($user_id)
	{
		$this->db->where('user_id',$user_id);
		$result = $this->db->count_all_results('user');
		//echo "dd". $result . "dd";
		if($result>0) return -1;
		else return 1;
	}
	
	function _check_signup()
	{
		
		if($this->input->post())
		{
			$user_id = $this->input->post('user_id',TRUE);
			$password = $this->input->post('password',TRUE);
			$password_confirm = $this->input->post('password_confirm',TRUE);
			$user_name = $this->input->post('user_name',TRUE);

			if(!$user_id || !$password || !$password_confirm || !$user_name) return -1;
			if($password != $password_confirm) return -2;
			if($this->_check_user_id($user_id)<0) return -3;
			
			return 1;
		}
	}
	
}

/* End of file user.php */
/* Location: ./application/controllers/user.php */